package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.hmdp.service.RedisLock;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisLockImpl implements RedisLock {

    private final StringRedisTemplate redisTemplate;

    public RedisLockImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 锁住的时候要在一定的时间释放
     *
     * @param key
     * @return
     */

    @Override
    public boolean tryLock(String key) {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    @Override
    public void unlock(String key) {
        redisTemplate.delete(key);
    }


}
